import { useState, useEffect, useRef, useMemo } from 'react';
import { useEditAddressField } from '@/pages/OrderModule/common/bizcomponents/EditAddress';
import GoodsListModal from '@/pages/GoodsModule/combinationGoods/component/GoodsListModal'
import SelectShopModal from '@/pages/OrderModule/common/bizcomponents/SelectShopModal';
import { GoodField } from '@/views/components/TableGoods';
import PackageAndGiveawayTabs from '@/pages/OrderModule/common/bizcomponents/PackageAndGiveawayTabs';
import CommonModal from '@/components/CommonModal';
import CommonTable from '@/components/CommonTable';
import { CommonText } from '@/pages/OrderModule/common/components/CommonText';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { Alert, Button, Form, Input, Image, InputNumber, Select, Space, Switch, Popover, Table, Popconfirm, message, Spin } from 'antd';
import IconFont from '@/components/IconFont';
import { find, cloneDeep, groupBy } from 'lodash';
import { getCurrentUser } from '@/utils/authority';
import { CommonForm, render2ColumnWithCollapse, withTitle } from '../../../../../common/components/CommonForm';
import Style from './index.module.less';
import { queryShopList, getGoodsSkuPageWithStar } from '@/services/common';
import { queryMultiRule, getRunVolumeGoodsOp, queryWarehouseList, queryCanUseExpressList, manualOrderOp, getMatchInfo } from '../../../../services';
import { formatSysImg, formatAmount } from '@/utils/utils.jsx';
import CommonLoading from '@/components/CommonLoading';
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import CommonTag from '@/components/CommonTag';
import orderUtils from '@/pages/OrderModule/common/utils/order';
import { IntInputNumber } from '@/components/CustomInput/index'
import { platformTypeName } from '@/utils/config';

const EmptyContent = () => {
  return <div style={{width:'100%', height:'100%', display:'flex', justifyContent:'center', alignItems:'center'}}>/</div>
}

const RenderSingleText = ({ text }) => {
  return <Popover content={<div style={{maxWidth:'420px',wordBreak:'break-all'}}>{text}</div>}>
    <div className='textOverflowMultiOne' style={{cursor:'pointer'}}>{text}</div>
  </Popover>
}

const checkFunc = (val) => {
  const bool = val <= 100000;
  if(!bool){
    message.destroy();
    message.info('限输入1- 100000的正整数');
  }
  return bool
}

const ManuallyOrdersModal = (props) => {
  const { handleOk, handleCancel } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [spinning, setSpinning] = useState(false);
  const [showTips, setShowTips] = useState('');
  const [isPacket, setIsPacket] = useState(false);
  const [data, setData] = useState([]);

  const [shopList, setShopList] = useState([]);
  const [warehouseList, setWarehouseList] = useState([]);
  const [expressList, setExpressList] = useState([]);

  const [shopSelected, setShopSelected] = useState({});
  const [warehouseSelected, setWarehouseSelected] = useState({});
  const [receiverAddress, setAddress] = useState({});

  const [visible, setVisible] = useState(false);
  const [scanData, setScanData] = useState([
    // {
    //   spuCode: 'spuCode'.repeat(30),
    //   skuCode: 'skuCode'.repeat(30),
    //   skuName: 'skuName'.repeat(30),
    //   supplierSkuSpecs: 'supplierSkuSpecs'.repeat(30),
    // }
  ]);
  const [updateKey, setUpdateKey] = useState(0);
  const [resetKey, setResetKey] = useState(0);

  const renderScanData = () => {

    const handleChange = (value, index) => {
      scanData[index].goodsNum = value;
    }

    const handlePressEnter = async () => {
      const newArr = cloneDeep(data), filterAddArr = [], combineGoodsIds = []
      let isRepeat = false, source = {};
      scanData.map(item=>{
        if(item.goodsNum){
          const isExitObj = find(newArr, ['id', item.id]);
          if(isExitObj){
            isRepeat = true;
          }else{
            filterAddArr.push(item);
            if(item.combinationSubList?.length){
              combineGoodsIds.push(item.id);
            }
            // const goodsNum = parseInt(item.goodsNum);
            // item.goodsNum = (goodsNum < 1000000 && goodsNum > 0) ? goodsNum : 1;
            // newArr.push(orderUtils.formatGoodsInfo(item));
          }
        }
      })
      if(isRepeat){
        message.info('重复添加的商品编码，已跳过！');
      }
      if(combineGoodsIds?.length){
        const res = await getMatchInfo({ids:combineGoodsIds});
        source = groupBy(res?.data || [], 'id');
      }
      if(filterAddArr?.length){
        filterAddArr.map(item=>{
          if(item.combinationSubList?.length){
            newArr.push(...(orderUtils.formatCombineGoodsInfo(source[item.id]?.[0], item.goodsNum) || []));
          }else{
            newArr.push(orderUtils.formatGoodsInfo({...item, num: item.goodsNum}));
          }
         })
         setData(orderUtils.sortGoodsByGoodsType(newArr));
      }
      setScanData([]);
    }

    const columns = [
      {
        title: '款式编码',
        dataIndex: 'spuCode',
        key: 'spuCode',
        width: 120,
        render: text => <RenderSingleText text={text} />
      },
      {
        title: '商品编码',
        dataIndex: 'skuCode',
        key: 'skuCode',
        width: 120,
       render: text => <RenderSingleText text={text} />
      },
      {
        title: '数量',
        dataIndex: 'goodsNum',
        key: 'goodsNum',
        width: 140,
        render: (text, record, index) => <IntInputNumber handleChange={(value)=>handleChange(value, index)} onPressEnter={handlePressEnter} checkFunc={checkFunc}/>
        // render: (text, record, index) => <InputNumber
        //   onChange={(value)=>handleChange(value, index)}
        //   onPressEnter={(e)=>handlePressEnter(e.target.value, index)}
        // />
      },
      {
        title: '系统商品名称',
        dataIndex: 'skuName',
        key: 'skuName',
        width: 200,
       render: text => <RenderSingleText text={text} />
      },
      {
        title: '颜色规格',
        dataIndex: 'colorSpecifications',
        key: 'colorSpecifications',
        width: 160,
       render: text => <RenderSingleText text={text} />
      },
   ]
    const tableProps = {
      columns,
      data: scanData,
      zIndex: 100,
      scroll:{y:260}
    }
    return <CommonTable {...tableProps} />
  }

  const stageParams = useRef({
    runVolumeGoods: {},//跑量商品
    addOrderIds: [],//新增订单id
  })

  const { runVolumeGoods } = stageParams.current;

  const currentUuid = useMemo(() => {
    return getCurrentUser()?.uuid;
  }, [])

  const isZifa = useMemo(() => {
    return warehouseSelected.uuid == currentUuid;
  }, [warehouseSelected])

  const totalWeight = useMemo(() => {
    const totalWeight = data.reduce((prev, next) => {
      return prev + (next.goodsWeight || 0) * 1000;
    }, 0);
    return totalWeight / 1000 || 1;
  }, [data])

  //基础信息获取
  useEffect(() => {
    getMultiRule();
    getStorelist();//店铺列表
    getWarehouseList();//发货仓列表
    const dom = document.getElementsByClassName('manual-modal')?.[0];
    if(dom){
      dom.addEventListener('click', function(){
        setScanData([])
      })
    }
    return ()=>{
      dom?.removeEventListener('click', function(){});
    }
  }, [])

  //获取并展示跑量商品
  useEffect(() => {
    if (isPacket) {
      switchRunVolumeGoods();
    } else if (data?.length) {
      setData([]);
    }
  }, [isPacket])

  useEffect(() => {
    if (data?.length) {
      console.log(data)
    }
  }, [data])

  //更新快递及计费
  useEffect(() => {
    if (Object.keys(shopSelected)?.length && Object.keys(warehouseSelected)?.length) {
      getExpressList();
    } else if (expressList?.length) {
      setExpressList([]);
    }
  }, [shopSelected, warehouseSelected, receiverAddress, data])

  //查询代发渠道多件订单限制
  const getMultiRule = async () => {
    const { success, data = {} } = await queryMultiRule();
    if(success) {
      if(data.multiProhibit && !Object.keys(data?.excludeUser || {}).includes(currentUuid+'')){
        setShowTips(data?.information);
      }
    }
  }

  //获取并展示跑量商品
  const switchRunVolumeGoods = async () => {
    const type = isZifa ? 'zifa' : 'daifa';
    // if (runVolumeGoods[type]) {
    //   return setData(runVolumeGoods[type]);
    // }
    setLoading(true);
    const { success, data = [] } = await getRunVolumeGoodsOp(type);
    setLoading(false);
    if (success) {
      if(!data?.length){
        return message.info('您还暂未设置跑量商品');
      }
      const runGoods = [];
      if(type == 'zifa'){
        const obj = find(data, ['runningVolumeStatus', 2]);
        if(obj){
          runGoods.push(orderUtils.formatZifaRunGoods(obj));
        }else{
          message.info('请先设置默认自发跑量商品');
        }
      }else{
        (data || []).map(item => {
          runGoods.push(orderUtils.formatDaifaRunGoods(item))
        });
      }
      stageParams.current.runVolumeGoods[type] = runGoods;
      setData(runGoods);
    }
  }

  //店铺列表数据
  const getStorelist = async () => {
    const { success, data = [] } = await queryShopList();
    const arr = data.filter(item => item.type != 28); //过滤掉得物平台
    if (success) {
      setShopList(arr.map(item=>{
        item.showStoreName = `${item.storeName}【${platformTypeName[item.type]}】`
        return item;
      }));
    }
  }

  //发货仓列表数据
  const getWarehouseList = async () => {
    const { success, data = [] } = await queryWarehouseList();
    if (success) {
      setWarehouseList(data.map(item=>{
        item.showWarehouseName = `${item.warehouseName} (${item.isOpen ? '代发' : '自发'})`;
        return item;
      }));
    }
  }

  //快递列表数据
  const getExpressList = async () => {
    const { province, city, area, address } = form.getFieldsValue();
    if (!province || !city || !area || !address) return;

    const { id: ecStoreId, type: orderChannel } = shopSelected, { id: warehouseId, uuid } = warehouseSelected;

    const { success, data = [] } = await queryCanUseExpressList({
      ecStoreId,
      orderChannel,
      warehouseId,
      areaId: area,
      receiverAddress: {
        province: receiverAddress.province,
        city: receiverAddress.city,
        district: receiverAddress.area,
        detail: receiverAddress.address,
      },
      weight: totalWeight,
      uuid: currentUuid,
      expressUuid: uuid,
      expressKind: isPacket ? 'PAO_LIANG' : 'OTHER',
      sendType: isZifa ? 'OWNER' : 'DAI_FA',
    });
    if (success) {
      setExpressList(data.map(item=>{
        item.showExpressName = `${formatAmount(item.postMoney)}-${item.baseExpressName}`;
        return item;
      }));
      const { baseExpressId } = form.getFieldsValue();
      if(baseExpressId && (!data?.length || !data.some(item=>item.baseExpressId == baseExpressId))){
        form.setFieldsValue({baseExpressId: undefined});//清除快递表单项
      }
    }
  }

  //提交保存
  const handleSave = async (bool) => {
    form.validateFields().then(async values => {
      if(!isPacket && !data.some(item=>item.orderGoodsType == 'goods')){
        return message.info('商品不能为空');
      }
      const { baseExpressId, user: orderReceiverName, phone: orderReceiverPhone, province, city, area, address, ...arg } = values;

      const { id: ecStoreId, storeName: ecStoreName, type: orderChannel } = shopSelected,
        { warehouseName, type: warehouseType, uuid: warehouseUuId } = warehouseSelected,
        { postMoney: feeAmount, expressUuid: logisticsuuId, baseExpressName: logisticsCompany,
          expressNetworkId: logisticsTmePlateId } = find(expressList, ['baseExpressId', baseExpressId]) || {};

     const goodsList = [], subList = [];
     data.map(item=>{
      if(item.isSysComposeGoods){
        subList.push({
          ...item,
          storeName: item.storeName == '/' ? '' : item.storeName
        });
      }else{
        goodsList.push({
          ...item,
          storeName: item.storeName == '/' ? '' : item.storeName
        });
      }
     })

      const params = {
        //表单
        ...arg,
        //店铺
        ecStoreId,
        ecStoreName,
        orderChannel,
        ecStoreType: orderChannel > 1 ? 1 : 0,
        type: warehouseUuId ? (currentUuid == warehouseUuId ? 0 : 1) : undefined, //0自发1代发
        isPacket: Number(isPacket),
        uuid: currentUuid,
        //发货仓
        warehouseName,
        warehouseType,
        warehouseUuId,
        //快递
        feeAmount,
        logisticsuuId,
        logisticsCompany,
        logisticsId: baseExpressId,
        logisticsTmePlateId,
        //收件信息
        orderReceiverName,
        orderReceiverPhone,
        areaId: area,
        location: {
          province: receiverAddress.province,
          city: receiverAddress.city,
          district: receiverAddress.area,
          receiverAddress: address,
          originProvinceId: province,
          originCityId: city,
          originDistrictId: area,
          isPlaintext: 1
        },
        //商品信息
        goodsList,
        subList
      };
      // console.log(params);
      // return
      setLoading(true);
      const { success, data: newOrderId } = await manualOrderOp(params);
      setLoading(false);
      if (success) {
        message.success('订单创建成功');
        if(bool){
          stageParams.current.addOrderIds.push(newOrderId);
          setData([]);
          setResetKey(resetKey+1);
          form.resetFields();
        }else{
          setSpinning(true);
          setTimeout(()=>{
            setSpinning(false);
            handleOk(2);
          }, 0)
        }
      }
    }).catch(err => message.info('必填字段不能为空'))
  }

  const { field, ...arg } = useEditAddressField({
    collapseAble: true,
    form,
    resetKey,
    title: {
      symbol: true,
      title: '收件信息',
    },
    onChange: (value, option, type) => {
      receiverAddress[type] = option.name;
      setAddress({ ...receiverAddress });
    },
    onRecognize(res){
      const { name, mobPhone, proObj, cityObj, areaObj, address } = res || {};
      setAddress({
        address,
        province: proObj?.name,
        city: cityObj?.name,
        area: areaObj?.name,
       });
      //  console.log(res)
       const value = form.getFieldsValue();
       form.resetFields();
       form.setFieldsValue({
        ...value,
        user: name,
        phone: mobPhone,
        address,
        province: proObj?.id,
        city: cityObj?.id,
        area: areaObj?.id,
       })
    }
  });

  function withLastRender(renderFn, node) {
    return (v, record, index, ...args) => {
      if (index === data.length - 1) {
        return node;
      }

      return renderFn(v, record, index, ...args);
    };
  }

  //开关切换
  function handleCheckSwitch(bool) {
    if (bool && !form.getFieldValue('warehouseId')) {
      return message.info('请先选择发货仓');
    }
    setIsPacket(bool);
  }

  //回车事件
  const handlePress = async (value) => {
    const skuCode = value?.replace(/\s/g, '');
    if(skuCode){
      setLoading(true);
      const { data, success} = await getGoodsSkuPageWithStar({ skuCode });
      setLoading(false);
      if(success){
        const goodsSource = data?.records || []
        if(goodsSource?.length){
          setScanData(goodsSource);
        }else{
          scanData?.length && setScanData([]);
          message.info('未找到该系统商品编码的商品');
        }
      }
    }
    form.setFieldsValue({ skuCode: '' });
    setUpdateKey(updateKey+1);
  }

  //下拉选中
  const handleSelected = (type, id) => {
    // console.log(type, id)
    if (type == 'shop') {
      const obj = find(shopList, ['id', id]);
      obj && setShopSelected(obj);
    } else {
      const obj = find(warehouseList, ['id', id]);
      obj && setWarehouseSelected(obj);
    }
  }

  const selectRowKeys = useRef([]);

  //添加商品modal props
  const addGoodsModalProps = {
    type:2,
    submitCallback:()=>{},
    handleSubmitAllInfo: async (addArr, numObj) => {

      const newArr = cloneDeep(data), filterAddArr = [], combineGoodsIds = [];//11901
      let isRepeat= false, source = {};
       addArr.map(item=>{
         const obj = find(newArr, ['id', item.id]);
         if(obj){
          isRepeat = true;
         }else{
          filterAddArr.push(item);
          // filterAddArr.push(orderUtils.formatGoodsInfo(item));
         }
         if(item.combinationSubList?.length){
          combineGoodsIds.push(item.id);
          // console.log(groupBy(item.combinationSubList, 'id'));
         }
       })
       if(isRepeat){
          message.info('重复添加的商品编码，已跳过！');
        }
       if(combineGoodsIds?.length){
         const res = await getMatchInfo({ids:combineGoodsIds});
         source = groupBy(res?.data || [], 'id');
       }
       if(filterAddArr?.length){
        filterAddArr.map(item=>{
          if(item.combinationSubList?.length){
            newArr.push(...(orderUtils.formatCombineGoodsInfo(source[item.id]?.[0], item.goodsNum) || []));
          }else{
            newArr.push(orderUtils.formatGoodsInfo(item));
          }
         })
        setData(orderUtils.sortGoodsByGoodsType(newArr));
       }

      // selectRowKeys.current = newArr.reduce((prev, next) => {
      //   return prev.concat(next.id);
      // }, [])
    },
    setSelectedRows: (dataSource, rowKey) => {
      // const ids = selectRowKeys.current, filterIds = [];
      // dataSource.map(item => {
      //   const id = item[rowKey];
      //   if (ids?.includes(id)) {
      //     filterIds.push(id);
      //   }
      // });
      return [];
    },
    getInputNumberValues: (value) => { }
  }

  //更改商品数量
  // const handleNumChange = (e, index) => {
  //   const val = Number(e.target.value);
  //   const reg = /^[1-9]\d*$/;
  //   if (val == data[index].goodsNum) {
  //     return;
  //   }
  //   const arr = cloneDeep(data)
  //   if (reg.test(val) && val < 100000) {
  //     arr[index].goodsNum = val;
  //     arr[index].amount = arr[index].goodsPrice * 1000 * val / 1000;
  //   } else {
  //     arr[index].goodsNum = 1;
  //     arr[index].amount = arr[index].goodsPrice;
  //     message.info("限输入1-100000的正整数");
  //   }
  //   setData(arr)
  // };

  const handleNumChange = (val, index) => {
    const arr = cloneDeep(data);
    arr[index].goodsNum = Number(val);
    arr[index].amount = Number(arr[index].goodsPrice) * 1000 * Number(val) / 1000;
    setData(arr);
  };

  //删除商品
  const handleDeleteGoods = (index) => {
     const arr = [...data];
     arr.splice(index, 1);
     setData(arr);
  }

  const baseColumns = [
    {
      title: '图片',
      dataIndex: 'goodsImage',
      width: 56,
      render: (value, record) => <Image src={formatSysImg(record.goodsImage, record.storeId)} width={48} height={48}/>
    },
    {
      title: '商品名称/款式编码/商品编码',
      dataIndex: 'field2',
      width: 200,
      render: (value, record) => {
        const orderGoodsTypesDesc = {
          runPackage: '【跑量包装】',
          runGoods: '【跑量商品】',
          package: '【包装】',
          gifts: '【赠品】',
        }
        return (<>
          <GoodField
            record={{
              name: `${orderGoodsTypesDesc[record.orderGoodsType] || ''}${record.goodsName}`,
              color: record.specs,
              goods: record.spuCode,
              style: record.skuCode,
            }}
            config={{
              image: 'none',
              info: ['name', 'color', 'goods', 'style'],
            }}
          />
          {!!record?.isSysComposeGoods &&
          // <Popover
          //   zIndex={1000}
          //   overlayStyle={{width:'880px'}}
          //   content={<CombineGoods data={record?.combinationSubList || []} />}
          //   placement='topLeft'
          //   >
          //   <span style={{cursor:'pointer'}}>
              <CommonTag type='zuhe' />
          //   </span>
          // </Popover>
          }
        </>
        );
      }
    },
    {
      title: '数量',
      dataIndex: 'goodsNum',
      width: 70,
      render: (text, record, index) =>{
        if(isPacket){
          return text
        }else{
          return <IntInputNumber defaultValue={text} handleChange={(value)=>handleNumChange(value, index)} checkFunc={checkFunc}/>
          // return <CommonInputNumber value={text} onBlur={e => handleNumChange(e, index)} placeholder="请输入数量" controls={false} />
        }
      }
    },
    {
      title: '供应商',
      dataIndex: 'storeName',
      width: 100,
      render: text =>{
        return text == '/' ? <EmptyContent /> : text;
      }
    },
    {
      title: '档口号',
      dataIndex: 'storeCode',
      width: 80,
    },
    {
      title: '采购价',
      dataIndex: 'goodsPrice',
      width: 90,
      render: (text, { isVipGoods }) => {
        return (<>
         <div className='common-color9'>￥{text}</div>
         {Boolean(isVipGoods) && <CommonTag type='isVipGoods' />}
        </>)
      }
    },
    {
      title: '金额',
      dataIndex: 'amount',
      width: 100,
      render: (text, { goodsNum, goodsPrice }) => `￥${text}`
    },
  ]

  const lastColumns = [
    {
      title: '操作',
      dataIndex: 'operator',
      width: 60,
      fixed:'right',
      render: (t, r, i) => {
        if(isPacket){
          return <EmptyContent />
        }
        return (
          <Popconfirm
            title="是否确认删除该商品？"
            onConfirm={() => handleDeleteGoods(i)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text">
              <Typography type="primary">删除</Typography>
            </Button>
          </Popconfirm>
        );
      }
    },
  ]

  //表格动态列
  const renderColumns = () => {
    if(isPacket){
      return [
        ...baseColumns,
        {
          title: '可用库存',
          dataIndex: 'availableInventory',
          width: 100,
          render: text => text || '/'
        },
      ...lastColumns];
    }else{
      return [...baseColumns, ...lastColumns];
    }
  }

  //弹窗关闭
  const onCancel = () => {
    const ids = stageParams.current.addOrderIds;
    if(ids.length){
      // handleOk(2, ids);//暂且全量刷新
      setSpinning(true);
        setTimeout(()=>{
          setSpinning(false);
          handleOk(2);
        }, 0)
    }else{
      handleCancel();
    }
  }

  const modalProps = {
    selectName: "add",
    showCustomizeGoods: true,
    memberPriceReadOnly: true,
    handleCancel() {
			setVisible(false);
      // handleCancel && handleCancel();
	  },
    async onGoodsSkuListSelected(addArr, isCustom) {
      console.log(addArr, isCustom)
      const newArr = cloneDeep(data), filterAddArr = [], combineGoodsIds = [];//11901
      let isRepeat= false, source = {};
       addArr.map(item=>{
         const obj = find(newArr, ['id', item.id]);
         if(obj){
          isRepeat = true;
         }else{
          filterAddArr.push(item);
          // filterAddArr.push(orderUtils.formatGoodsInfo(item));
         }
         if(item.type == 2){
          combineGoodsIds.push(item.id);
          // console.log(groupBy(item.combinationSubList, 'id'));
         }
       })
       if(isRepeat){
          message.info('重复添加的商品编码，已跳过！');
        }
       if(combineGoodsIds?.length){
         const res = await getMatchInfo({ids:combineGoodsIds});
         source = groupBy(res?.data || [], 'id');
       }
       if(filterAddArr?.length){
        filterAddArr.map(item=>{
          if(item.type == 2){
            newArr.push(...(orderUtils.formatCombineGoodsInfo(source[item.id]?.[0], item.num) || []));
          }else{
            if(isCustom) {
                newArr.push(orderUtils.formatCustomGoodsInfo(item));
            } else {
                newArr.push(orderUtils.formatGoodsInfo(item));
            }
          }
         })
        setData(orderUtils.sortGoodsByGoodsType(newArr));
       }
    },
     destroyOnClose: true
  }

  return (
    <>
      <CommonModal
        className='manual-modal'
        title='手工下单'
        visible={true}
        width={938}
        onCancel={onCancel}
        footer={[<Button key='cancel' onClick={onCancel}>取消</Button>, <Button type='primary' onClick={()=>handleSave(true)} key='ok'>确定并继续</Button>,
          <Button type='primary' onClick={()=>handleSave()} key='sure'>确定</Button>]}
        >
          <Spin spinning={spinning} tip="载入新订单中...">
          {
            showTips && (<Alert
              message={<span style={{ fontWeight: 700, fontFamily: 'serif' }}>代发渠道多件订单限制</span>}
              description={showTips}
              type="warning"
              style={{marginBottom:'8px'}}
              />)
          }
          
        <CommonForm
          formProps={{ form, autoComplete:'off', className: 'speccollapseForIcon' }}
          collapse={{ defaultActiveKey: ['baseInfo', 'addressInfo', 'goodsInfo'] }}
          columns={[
            withTitle({
              params: {
                title: {
                  symbol: true,
                  title: '跑量订单设置',
                },
                collapseAble: false,
              },
              column: [
                {
                  label: '是否为跑量订单',
                  name: 'field1',
                  Component: Switch,
                  props: {
                    checked: isPacket,
                    onChange: bool => handleCheckSwitch(bool),
                    style:{marginLeft:'12px', position:'relative', top: '-3px'}
                  },
                },
                {
                  block: <CommonText text="设为跑量订单，下列商品和包装会自动变为跑量商品、跑量包装和跑量快递" as="s1" type="info" style={{ marginBottom: 16 }}></CommonText>,
                },
              ],
            }),
            render2ColumnWithCollapse({
              params: {
                title: {
                  symbol: true,
                  title: '基本信息',
                },
                key: 'baseInfo',
                collapseAble: true,
              },
              columns: [
                [
                  {
                    block: (
                      <SelectShopModal
                        onChange={(data) => {
                          if (data) {
                            setShopSelected(data);
                            // setShopList([data]);
                          }
                          form.setFieldsValue({
                            'ecstoreId': data?.label
                          });
                        }}
                      >
                       <Form.Item name="ecstoreId" rules={[{required:true, message:'请选择店铺'}]} >
                          <Select open={false} placeholder={<span className='lable-require'>请选择店铺</span>} options={shopList} allowClear/>
                        </Form.Item>
                      </SelectShopModal>
                    ),
                  },
                  // {
                  //   label: '',
                  //   name: 'ecstoreId',
                  //   Component: Select,
                  //   props: {
                  //     placeholder: <span className='lable-require'>请选择店铺</span>,
                  //     options: shopList,
                  //     fieldNames: {
                  //       label: 'showStoreName',
                  //       value: 'id'
                  //     },
                  //     onChange: e => handleSelected('shop', e)
                  //   },
                  //   rules: [{ required: true, message: '请选择店铺' }],
                  // },
                  {
                    label: '',
                    name: 'warehouseId',
                    Component: Select,
                    props: {
                      allowClear: true,
                      placeholder: '请选择发货仓',
                      options: warehouseList,
                      fieldNames: {
                        label: 'showWarehouseName',
                        value: 'id'
                      },
                      disabled: isPacket,
                      onChange: e => handleSelected('warehouse', e)
                    },
                  },
                ],
                [
                  {
                    label: '',
                    name: 'baseExpressId',
                    // Component: Select,
                    render: ()=>{
                      return (<div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                        <Form.Item name='baseExpressId' style={{flex: 1}}>
                          <Select placeholder='请选择快递' allowClear>
                            {
                              expressList.map((d) => (
                                <Option className="smallFontSizeOption" label={d.showExpressName} key={d.showExpressName} value={d.baseExpressId}>
                                  {d.showExpressName}
                                </Option>
                              ))
                            }
                          </Select>
                        </Form.Item>
                        <div style={{width:"16px", cursor:'pointer', marginLeft:'6px', position:"relative", top: '-6px'}}>
                          <Popover content='请选择仓库、省市区、商品后再选择快递'><IconFont type='iconwenhao' style={{fontSize:"16px"}} /></Popover>
                        </div>
                      </div>)
                    },
                    props: {
                      placeholder: '请选择快递',
                      options: expressList,
                      fieldNames: {
                        label: 'showExpressName',
                        value: 'baseExpressId'
                      },
                      suffixIcon: <Popover content='请选择仓库、省市区、商品后再选择快递'><IconFont type='iconwenhao'/></Popover>
                    },
                  },
                  {
                    label: '',
                    name: 'orderRemark',
                    Component: Input,
                    props: {
                      placeholder: '订单备注',
                      maxLength: 120,
                      showCount: true
                    },
                  },
                ],
              ],
            }),
            field,
            render2ColumnWithCollapse({
              params: {
                title: {
                  symbol: true,
                  title: '订单商品',
                },
                key: 'goodsInfo',
                collapseAble: true,
              },
              columns: [
                [
                  {
                    block: <></>,
                  },
                  {
                    block: <></>,
                  },
                ],
              ],
            }),
          ]}
        />
        <Popover zIndex={1000} overlayStyle={{width:'880px'}} content={renderScanData()} title={<div style={{fontWeight:'bold'}}>输入您想要的商品数量后回车</div>} open={scanData?.length} placement='topLeft'>
           <>
            <Input disabled={isPacket} placeholder = '请输入系统商品编码' onPressEnter={(e)=>handlePress(e.target.value)} style={{width:'432px', marginBottom:'4px'}} maxLength={200} key={updateKey} />
            <p style={{textIndent:'6px', fontSize:13, color:'#aaa', marginBottom:'16px'}}>默认精准匹配，结尾输入*进行模糊匹配</p>
           </>
         </Popover>
        {
          isPacket ? (<>
           <Space className={Style.common_gap}>
            <Button type="ghost"  onClick={()=>message.info('跑量订单无需添加商品')}> 添加商品</Button>
            <Button type="ghost"  onClick={()=>message.info('跑量订单无需添加包装赠品')}>添加包装或赠品</Button>
          </Space>
          </>) : (<>
         <Space className={Style.common_gap}>
            {/* <GoodsSelectModal {...addGoodsModalProps}> */}
              <Button type="ghost" onClick={()=>setVisible('addGoods')}>
                添加商品
              </Button>
            {/* </GoodsSelectModal> */}
            <Button type="ghost" onClick={(e)=>setVisible('addPacking')}>
              添加包装或赠品
            </Button>
          </Space>
          </>)
        }

        <Table
          columns={renderColumns()}
          dataSource={data}
          pagination={false}
          bordered
          scroll={{ y: 500 }}
          rowKey='id'
          summary={pageData => {

            let totalNumber = 0, totalAmount = 0;
            pageData.map(item => {
              totalNumber += Number(item.goodsNum) || 1;
              totalAmount += item.amount * 1000;
            })

            return (
              <Table.Summary.Row>
                <Table.Summary.Cell>总计</Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell>{totalNumber}</Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
                <Table.Summary.Cell><span style={{ fontWeight: 500 }}>{formatAmount(totalAmount / 1000)}</span></Table.Summary.Cell>
                <Table.Summary.Cell></Table.Summary.Cell>
              </Table.Summary.Row>
            );
          }}
        />
        </Spin>
      </CommonModal>
      <CommonModal
        title= '添加包装或赠品'
        visible={visible == 'addPacking'}
        width = {856}
        onOk= {()=>{
          const newArr = cloneDeep(data);
          stageParams.current.packageSource.map(item=>{
            const obj = find(newArr, ['goodsId', item.goodsId]);
            if(!obj){
              const { goodsCommonid, goodsId, goodsPrice  } = item;
             newArr.push({
              ...item,
              goodsNum: item.goodsNum || 1,
              type: item.orderGoodsType == 'package' ? 0 : 1,
              goodsCode: goodsId,
              amount: goodsPrice * 1000 * (item.goodsNum || 1) / 1000,
              isCustom: 0,
              isVipGoods: 0,
              outStoreSku: goodsId,
              outStoreSpu: goodsCommonid,
             });
            }
          })
         setData(orderUtils.sortGoodsByGoodsType(newArr));
         setVisible(false);
        }}
        onCancel={()=>setVisible(false)}
        >
          {
            visible == 'addPacking' && <PackageAndGiveawayTabs
            onSelectionChange={(list)=>{stageParams.current.packageSource = list;} }
          />
          }
      </CommonModal>
      { visible == 'addGoods' && <GoodsListModal {...modalProps} />}
      <CommonLoading loading={loading} />
    </>
  );
};

export default ManuallyOrdersModal;
